/**
 * 
 */
package com.gmail.blackdog1987.carcare.activity;

import in.srain.cube.image.CubeImageView;
import in.srain.cube.image.ImageLoader;
import in.srain.cube.image.ImageLoaderFactory;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gmail.blackdog1987.carcare.App;
import com.gmail.blackdog1987.carcare.BaseActivity;
import com.gmail.blackdog1987.carcare.R;
import com.gmail.blackdog1987.carcare.adapter.OrderMeiRongAdapter;
import com.gmail.blackdog1987.carcare.db.dao.UserDao;
import com.gmail.blackdog1987.carcare.entity.TMaintain;
import com.gmail.blackdog1987.carcare.entity.TMaintainDetail;
import com.gmail.blackdog1987.carcare.entity.TProduct;
import com.gmail.blackdog1987.carcare.network.request.builder.MeirongDetailRequestBuilder;
import com.gmail.blackdog1987.carcare.network.request.builder.OrderMeirongRequestBuilder;
import com.gmail.blackdog1987.carcare.network.response.IResponse;
import com.gmail.blackdog1987.carcare.network.response.MeirongDetailResponse;
import com.gmail.blackdog1987.carcare.network.response.OrderMeirongResponse;
import com.gmail.blackdog1987.carcare.network.response.handler.IResponseHandler;
import com.gmail.blackdog1987.carcare.network.response.handler.MeirongDetailResponseHandler;
import com.gmail.blackdog1987.carcare.network.response.handler.OnResponseListener;
import com.gmail.blackdog1987.carcare.network.response.handler.OrderMeirongResponseHandler;

public class OrderMeiRongActivity extends BaseActivity implements OnResponseListener, OnClickListener {
	private Context mContext;
	private ListView mListView;
	private TextView mDistance;
	private TextView mTitle;
	private TextView mPrice;
	private CubeImageView mHead;
	private CheckBox mAll;
	private View mPay;
	private OrderMeiRongAdapter mAdapter;
	private TMaintain mObj;
	private MeirongDetailRequestBuilder mReq = new MeirongDetailRequestBuilder();
	private MeirongDetailResponseHandler mHandler = new MeirongDetailResponseHandler();

	private OrderMeirongRequestBuilder mOrderReq = new OrderMeirongRequestBuilder();
	private OrderMeirongResponseHandler mOrerHandler = new OrderMeirongResponseHandler();
	private float price;
	TMaintain data;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_meirong);
		mContext = this;

		initViews();
		initData(savedInstanceState);
		reg();
	}

	public void initViews() {
		mDistance = (TextView) findViewById(R.id.order_meirong_distance);
		mHead = (CubeImageView) findViewById(R.id.order_meirong_head);
		mTitle = (TextView) findViewById(R.id.order_meirong_title);
		mListView = (ListView) findViewById(R.id.order_meirong_list);
		mAll = (CheckBox) findViewById(R.id.order_meirong_all);
		mPrice = (TextView) findViewById(R.id.order_meirong_cost);
		mPay = findViewById(R.id.order_meirong_pay);

	}

	public void addPrice(double price) {
		this.price += price;
		mPrice.setText(String.valueOf(this.price));
	}

	public void cancelAll() {
		if (mAll.isChecked()) {
			mAll.setChecked(false);
		}
	}

	public void reg() {
		findViewById(R.id.back).setOnClickListener(this);
		mHandler.setOnResponseListener(this);
		mAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					mAdapter.selectAll();
				}
			}
		});
		mPay.setOnClickListener(this);
		mOrerHandler.setOnResponseListener(this);
		findViewById(R.id.order_meirong_location).setOnClickListener(this);
		findViewById(R.id.order_meirong_call).setOnClickListener(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.setOnResponseListener(null);
		mHandler = null;
	}

	public void initData(Bundle savedInstanceState) {
		data = (TMaintain) getIntent().getSerializableExtra("data");
		if (data == null) {
			Toast.makeText(mContext, "unknown error", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		mAdapter = new OrderMeiRongAdapter(this, null);
		mListView.setAdapter(mAdapter);
		mReq.setMaintainid(data.getId()).postJsonRequest(mContext, mHandler);

		/**
		 * test
		 */
		// List<TMaintainDetail> details = new ArrayList<TMaintainDetail>();
		// for (int i = 0; i < 5; i++) {
		// TMaintainDetail detail = new TMaintainDetail();
		// detail.setId(new Random().nextInt());
		// detail.setPrice(new Random().nextFloat());
		// detail.setInfo("备注："+new Random().nextInt());
		// detail.setMaintainId(mObj.getId());
		// detail.setTitle("名字 : " + i);
		// details.add(detail);
		// }
		// mAdapter.setDatas(details);
		if (data.headurl != null && data.headurl.length() != 0) {
			ImageLoader imageLoader = ImageLoaderFactory.create(mContext);
			mHead.loadImage(imageLoader, data.headurl);
		}
		mDistance.setText("289m");
		mTitle.setText(data.getTitle());
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.order_meirong_call:
			if(data.phone==null||data.phone.length()==0){
				Toast.makeText(mContext, "尚未录入商家电话", Toast.LENGTH_LONG).show();
				return;
			}
			Intent callintent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+data.phone));  
            startActivity(callintent);
			
			break;
		case R.id.order_meirong_location:
			Intent intent = new Intent(OrderMeiRongActivity.this, MapGuidActivity.class);
			intent.putExtra("lat", data.lat);
			intent.putExtra("lng", data.lon);
			startActivity(intent);
			break;
		case R.id.back:
			finish();
			break;
		case R.id.order_meirong_pay:
			if (!App.validUser(OrderMeiRongActivity.this))
				return;
			String detailid = "";
			for (int i = 0; i < mAdapter.getSelected().size(); i++) {
				detailid = detailid + "," + mAdapter.getSelected().get(i).getId();
			}
			detailid = detailid.replaceFirst(",", "");
			if (detailid == null || detailid.length() == 0) {
				Toast.makeText(mContext, "请选择商品", Toast.LENGTH_LONG).show();
				return;
			}
			mOrderReq.setDetailid(detailid).setMaintainid(String.valueOf(data.getId())).setUserid("1").postJsonRequest(mContext, mOrerHandler);
			break;
		default:
			break;
		}

	}

	@Override
	public void onResponse(IResponseHandler classz) {
		IResponse res = classz.getResponse();
		if (res instanceof MeirongDetailResponse) {
			List<TMaintainDetail> details = ((MeirongDetailResponse) classz.getResponse()).datas;
			if (details == null || details.size() == 0) {
				Toast.makeText(mContext, "没有找到合适的选项", Toast.LENGTH_LONG).show();
			} else {
				mAdapter.setDatas(details);
			}
		} else if (res instanceof OrderMeirongResponse) {
			TProduct product = new TProduct();
			product.body = "汽车护理";
			product.price = ((OrderMeirongResponse) classz.getResponse()).order.totalprice;
			product.subject = data.title;
			product.table = "t_order_maintain";
			product.tableId = ((OrderMeirongResponse) classz.getResponse()).order.getId();
			product.userid = new UserDao().getUser().id;
			Intent i = new Intent(OrderMeiRongActivity.this, PayActivity.class);
			i.putExtra("data", product);
			startActivityForResult(i, PayActivity.REQUESTCODE_PAY);
		}
		// insert db
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case PayActivity.REQUESTCODE_PAY:
				Toast.makeText(mContext, "恭喜您支付成功", Toast.LENGTH_LONG).show();
				finish();
				break;
			}
		}
	}

	@Override
	public void onError(IResponseHandler classz) {
		IResponse res = classz.getResponse();
		if (res instanceof MeirongDetailResponse) {
			Toast.makeText(mContext, "没有找到合适的选项", Toast.LENGTH_LONG).show();
		} else if (res instanceof OrderMeirongResponse) {
			Toast.makeText(mContext, "下单失败！", Toast.LENGTH_LONG).show();
		}
	}
}
